﻿using System.ComponentModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;

namespace Microsoft.Services.Clab.UI.Mvvmc.Presentation
{
    public class WpfViewBase : UserControl, IView
    {
        public WpfViewBase()
        {
            this.Initialized += (s, e) => WpfViewHelper.OnControlInitialized(s as IView, (bool)DesignerProperties.IsInDesignModeProperty.GetMetadata(this).DefaultValue);
            this.Loaded += (s, e) => WpfViewHelper.OnControlLoaded(s as IView);
        }

        protected override void OnContentChanged(object oldContent, object newContent)
        {
            base.OnContentChanged(oldContent, newContent);
            WpfViewHelper.OnContentChanged(this, oldContent, newContent);
        }

        protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
        {
            base.OnPropertyChanged(e);
            WpfViewHelper.UpdatePropertyMapping(this, e.Property);
        }

        #region IView Members

        public void Initialize(IViewModel viewModel)
        {
            WpfViewHelper.InitializeView(this, viewModel);
        }

        #region ViewModel Property
        public IViewModel ViewModel
        {
            get { return this.viewModel; }
            set { if (this.viewModel != value) { this.viewModel = value; this.OnPropertyChanged("ViewModel"); } }
        }
        private IViewModel viewModel;
        #endregion

        #region State Property
        public ViewState State
        {
            get { return this.state; }
            set { if (this.state != value) { this.state = value; this.OnPropertyChanged("State"); } }
        }
        private ViewState state;
        #endregion

        #endregion

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string name)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(name));
            }
        }

        #endregion

        #region Dispose pattern

        ~WpfViewBase()
        {
            this.Dispose(false);
        }

        public void Dispose()
        {
            WpfViewHelper.Dispose(this, v => v.Dispose(true));
        }

        protected virtual void Dispose(bool disposing)
        {
        }

        #endregion
    }
}
